package com.xm.xmapp.fragment;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.xm.xmapp.FeedbackActivity;
import com.xm.xmapp.ImageBucketChooseActivity;
import com.xm.xmapp.MipcaActivityCapture;
import com.xm.xmapp.R;
import com.xm.xmapp.ShowImageActivity;
import com.xm.xmapp.adapter.FeedbackProblemAdapter;
import com.xm.xmapp.adapter.ImagePublishAdapter;
import com.xm.xmapp.adapter.ImagePublishAdapter.RemoveDataListener;
import com.xm.xmapp.app.CodeConstant;
import com.xm.xmapp.app.MyAppcation;
import com.xm.xmapp.app.Type.F_PileFeedBack;
import com.xm.xmapp.base.BaseFragment;
import com.xm.xmapp.dialog.SelectPhotoDialog;
import com.xm.xmapp.dialog.SelectPhotoDialog.OnClickPhoto;
import com.xm.xmapp.myinterface.DisssmissInterFace;
import com.xm.xmapp.myinterface.GetDataInterFace;
import com.xm.xmapp.myinterface.ListViewOnclickInterFace;
import com.xm.xmapp.request.bean.Feedback_Problem_CategoryRequest;
import com.xm.xmapp.request.bean.UserFeedbackRequest;
import com.xm.xmapp.response.bean.CustomImageItem;
import com.xm.xmapp.response.bean.ResponseFeedbackProblem;
import com.xm.xmapp.tools.ImageTool;
import com.xm.xmapp.tools.ScreenUtils;
import com.xm.xmapp.tools.Tools;

public class PileFeedBackFragment extends BaseFragment implements OnClickListener {

	private Feedback_Problem_CategoryRequest requestBean;
	private int problem_type;
	private GridView gridView;
	private ArrayList<ResponseFeedbackProblem> list = new ArrayList<ResponseFeedbackProblem>();
	private FeedbackProblemAdapter problemAdapter;
	private ArrayList<ResponseFeedbackProblem> moreList = new ArrayList<ResponseFeedbackProblem>();
	private GridView mGridView;
	private ImagePublishAdapter adapter;
	private List<CustomImageItem> mDataList = new ArrayList<CustomImageItem>();

	private EditText number, problem_des;
	private UserFeedbackRequest userFeedback;
	private TextView tv_tip;
	private RemoveDataListener mRemoveDataListener;

	public PileFeedBackFragment() {
		super();
		isSuppertLazyLoad = false;
	}

	public void setProblem_type(int problem_type) {
		this.problem_type = problem_type;
	}

	@Override
	public int setContentView() {

		return R.layout.fragment_pilefeedback;
	}

	@Override
	public void initView() {

		gridView = (GridView) findViewById(R.id.gridView);
		mGridView = (GridView) findViewById(R.id.mGridView);
		number = (EditText) findViewById(R.id.number);
		problem_des = (EditText) findViewById(R.id.problem_des);
		tv_tip = (TextView) findViewById(R.id.tv_tip);
	}

	@Override
	public Object dataChang(int flag, Object data) {
		switch (flag) {
		case F_PileFeedBack.DEFAULT:
			ArrayList<CustomImageItem> incomingDataList = (ArrayList<CustomImageItem>) data;
			mDataList.addAll(incomingDataList);
			if (adapter == null) {
				adapter = new ImagePublishAdapter(getActivity(), mDataList, mRemoveDataListener);
				mGridView.setAdapter(adapter);
			}
			adapter.notifyDataSetChanged();
			tv_tip.setText("上传照片（" + mDataList.size() + "/6）");
			break;

		default:
			break;
		}

		return super.dataChang(flag, data);
	}

	public void setResult(JSONObject htmlResponse) throws Exception {

		if (htmlResponse.getInt("t") == 2) {
			String[] sourse = htmlResponse.getString("y").split("#");

			number.setText(sourse[1]);
			number.setEnabled(false);
		} else {
			Tools.showMessage("请切换至车辆扫码");
		}

	}

	public void addImage() {
		CustomImageItem item = new CustomImageItem();
		item.sourcePath = path;
		mDataList.add(item);
		if (adapter == null) {
			adapter = new ImagePublishAdapter(getActivity(), mDataList, mRemoveDataListener);
			mGridView.setAdapter(adapter);
		}
		adapter.notifyDataSetChanged();
		tv_tip.setText("上传照片（" + mDataList.size() + "/6）");
		Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		Uri uri = Uri.fromFile(new File(path));
		intent.setData(uri);
		context.sendBroadcast(intent);

	}

	@Override
	public void initData() {
		requestBean = new Feedback_Problem_CategoryRequest();
		requestBean.problem_type = problem_type;
		userFeedback = new UserFeedbackRequest();
		userFeedback.user_feedback_problem_category_id = 0;
		userFeedback.problem_descript = "其它";
		userFeedback.problem_type = 2;
		GetDataInterFace<String> listener = new GetDataInterFace<String>() {

			@Override
			public void onResponse(String response) {
				promptDialog.dismiss();
				List<ResponseFeedbackProblem> listBean = JSON.parseArray(response, ResponseFeedbackProblem.class);
				list.clear();
				moreList.clear();
				if (listBean.size() > 6) {

					for (int i = 0, size = listBean.size(); i < size; i++) {
						if (i < 5)
							list.add(listBean.get(i));
						else
							moreList.add(listBean.get(i));
					}

				} else {
					list.addAll(listBean);
				}
				ResponseFeedbackProblem bean = new ResponseFeedbackProblem();
				bean.problem_descript = "其它";
				bean.user_feedback_problem_category_id = 0;
				list.add(bean);
				userFeedback.user_feedback_problem_category_id = list.get(0).user_feedback_problem_category_id;
				userFeedback.problem_descript = list.get(0).problem_descript;
				problemAdapter.notifyDataSetChanged();

			}
		};
		DisssmissInterFace disssmissListener = new DisssmissInterFace() {

			@Override
			public void putError(VolleyError error) {
				promptDialog.dismiss();
			}
		};
		promptDialog.show();
		MyAppcation.getMyAppcation().getPostData(getActivity(), requestBean, listener, disssmissListener);
		problemAdapter = new FeedbackProblemAdapter(list, getActivity(), R.layout.item_feedbackproblem);
		ListViewOnclickInterFace listViewOnclickInterFace = new ListViewOnclickInterFace() {

			@Override
			public Object DoSomeThing(Object data) {
				
				ResponseFeedbackProblem bean = (ResponseFeedbackProblem) data;
				userFeedback.user_feedback_problem_category_id = bean.user_feedback_problem_category_id;
				userFeedback.problem_descript = bean.problem_descript;
				return null;
			}
		};
		problemAdapter.setIn(listViewOnclickInterFace);
		gridView.setAdapter(problemAdapter);

		mRemoveDataListener = new RemoveDataListener() {

			@Override
			public void dataChange() {
				tv_tip.setText("上传照片（" + mDataList.size() + "/6）");
			}
		};
		adapter = new ImagePublishAdapter(getActivity(), mDataList, mRemoveDataListener);
		mGridView.setAdapter(adapter);
		mGridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				
				if (position == getDataSize()) {
					SelectPhotoDialog selectPhotoDialog = new SelectPhotoDialog(getActivity());
					selectPhotoDialog.show();
					selectPhotoDialog.setL(new OnClickPhoto() {

						@Override
						public void takePhotoFromSrc() {

							Intent intent = new Intent(MyAppcation.getMyAppcation(), ImageBucketChooseActivity.class);
							intent.putExtra(CodeConstant.EXTRA_CAN_ADD_IMAGE_SIZE, getAvailableSize());
							intent.putExtra("flag", 1);
							startActivity(intent);
						}

						@Override
						public void takePhotoFramCamera() {

							takePhoto();
						}
					});
				} else {
					Intent intent = new Intent(MyAppcation.getMyAppcation(), ShowImageActivity.class);
					intent.putExtra("list", (Serializable) mDataList);
					intent.putExtra("position", position);
					startActivity(intent);
				}
			}
		});

	}

	private int getAvailableSize() {
		int availSize = CodeConstant.MAX_IMAGE_SIZE - mDataList.size();
		if (availSize >= 0) {
			return availSize;
		}
		return 0;
	}

	private String path = "";

	public String getPath() {
		return path;
	}

	SimpleDateFormat format = new SimpleDateFormat("yyyMMddHHmmss");

	public void takePhoto() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		File vFile = new File(CodeConstant.Photo_Path, String.valueOf(System.currentTimeMillis()) + ".jpg");
		if (!vFile.exists()) {
			File vDirPath = vFile.getParentFile();

			vDirPath.mkdirs();
		} else {
			if (vFile.exists()) {
				vFile.delete();
			}
		}
		path = vFile.getPath();
		Uri cameraUri = Uri.fromFile(vFile);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);

		startActivityForResult(openCameraIntent, CodeConstant.PileTakePhoto);
		FeedbackActivity.selectFlag = CodeConstant.PileTakePhoto;
	}

	private int getDataSize() {
		return mDataList == null ? 0 : mDataList.size();
	}

	@Override
	public void initEvent() {

		findViewById(R.id.saomiao).setOnClickListener(this);
		findViewById(R.id.submit).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.saomiao:
			Intent intent = new Intent(MyAppcation.getMyAppcation(), MipcaActivityCapture.class);
			intent.putExtra("flag", 3);
			getActivity().startActivityForResult(intent, PileInfoFragment.SCANNIN_GREQUEST_CODE);
			break;
		case R.id.submit:
			if (number.getText().toString().equals(""))
				Tools.showMessage("充电枪编号不能为空");
			else if (userFeedback.user_feedback_problem_category_id == 0
					&& problem_des.getText().toString().replaceAll(" ", "").equals("")) {
				Tools.showMessage("请输入您的问题描述或建议");
			} else {
				userFeedback.charging_equipment_interface_id = number.getText().toString();
				userFeedback.user_feedback_problem = problem_des.getText().toString();

				if (mDataList != null && mDataList.size() > 0) {
					promptDialog.show();
					for (int i = 0, size = mDataList.size(); i < size; i++) {
						Bitmap bitmap;
						String src = mDataList.get(i).sourcePath;
						if (ScreenUtils.getScreenWidth(getActivity()) > 720) {
							bitmap = ImageTool.getSmallBitmap(src, 720, 1280);
						} else {
							bitmap = ImageTool.getSmallBitmap(src, ScreenUtils.getScreenWidth(getActivity()),
									ScreenUtils.getScreenHeight(getActivity()));
						}
						if (bitmap != null) {
							String bitmapStr = "suffix:jpg;base64;" + ImageTool.Bitmap2StrByBase64(bitmap);
							switch (i) {
							case 0:
								userFeedback.img1 = bitmapStr;
								break;
							case 1:
								userFeedback.img2 = bitmapStr;
								break;
							case 2:
								userFeedback.img3 = bitmapStr;
								break;
							case 3:
								userFeedback.img4 = bitmapStr;
								break;
							case 4:
								userFeedback.img5 = bitmapStr;
								break;
							case 5:
								userFeedback.img6 = bitmapStr;
								break;

							default:
								break;
							}
						}
					}
					MyAppcation.getMyAppcation().getPostData(getActivity(), userFeedback,
							new GetDataInterFace<String>() {

								@Override
								public void onResponse(String response) {
									promptDialog.dismiss();
									getActivity().finish();
									Tools.showMessage("提交成功，感谢您的反馈");
								}
							}, new DisssmissInterFace() {

								@Override
								public void putError(VolleyError error) {
									promptDialog.dismiss();
								}
							});
				} else {
					Tools.showMessage("请至少上传一张照片");
				}

			}
			break;

		default:
			break;
		}
	}

}
